package com.lovo.homework0201.config;

import com.lovo.homework0201.dao.IPowerDao;
import com.lovo.homework0201.dao.IUserDao;
import com.lovo.homework0201.dao.IUserPowerDao;
import com.lovo.homework0201.entity.PowerEntity;
import com.lovo.homework0201.entity.UserEntity;
import com.lovo.homework0201.entity.UserPowerEntity;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    IUserDao userDao;
    @Autowired
    IUserPowerDao userPowerDao;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserEntity u = (UserEntity) principalCollection.getPrimaryPrincipal();
        //用用户查询权限
        List<UserPowerEntity> list = userPowerDao.findAllByUserAndPower(u.getUserId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        list.stream().filter(power -> power != null && !power.getPower().getPowerResource().equals(""))
                .forEach(
                        powerEntity ->
                                info.addStringPermission(powerEntity.getPower().getPowerResource())
                );
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        char[] passArray = token.getPassword();
        String username = token.getUsername();
        String password = String.valueOf(passArray);

        //从数据库查询用户是否存在
        UserEntity user = userDao.findByUserNameAndPassWord(username, password);
        if (null != user) {
            return new SimpleAuthenticationInfo(user, password, username);
        }
        return null;
    }
}
